package com.springboot.demo.design.pattern.operator.impl;

import com.springboot.demo.design.pattern.enums.FormEnum;
import com.springboot.demo.design.pattern.form.Form;
import com.springboot.demo.design.pattern.operator.Dispatcher;
import com.springboot.demo.design.pattern.operator.Practicer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

/**
 * 标准派发器
 *
 * @author supu
 * @date 2019-03-19 15:44
 **/
@Log4j2
@Component
public class StandardDispatcher implements Dispatcher {
    private Map<FormEnum, Practicer> practicerMap;

    private ReentrantLock reentrantLock = new ReentrantLock();

    public StandardDispatcher() {
        this.practicerMap = new ConcurrentHashMap<>();
    }

    @Override
    public boolean register(FormEnum formEnum, Practicer practicer) {
        try {
            reentrantLock.lock();
            if (practicerMap.containsKey(formEnum)) {
                log.error("{} register failed, because of {} is exist", formEnum.getValue(),
                        practicerMap.get(formEnum).getClass().getName());
                return false;
            }

            practicerMap.put(formEnum, practicer);
            return true;
        } catch (Exception e) {
            log.error("register get reentrantLock failed, error: {}", e);
            return false;
        } finally {
            reentrantLock.unlock();
        }
    }

    @Override
    public void operate(Form form) {
        Practicer practicer = practicerMap.get(form.getFormEnum());
        if (practicer == null) {
            log.error("{} binding practicer is not exist", form.getFormEnum().getValue());
        }
        practicer.operate(form);
    }
}
